import traceback
import logging

from django.shortcuts import render

# Create your views here.
from django.db.models import Q
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework import generics, mixins, views
from django_nameko import get_pool
from drf_yasg2.utils import swagger_auto_schema
from drf_yasg2 import openapi

from points_mall.models import PointsMallGoods, PointsMallPicture
from points_mall.serializers import PointsMallGoodsSerializer
from points_mall.utils import count_goods_points
from points_mall.points_forms import BuyGoodsForm, AddGoodsForm

from account.utils import update_inviter_code
from common.utils import LargeResultsSetPagination

logger = logging.getLogger('log')


class AddPointsGoods(generics.GenericAPIView):
    """
    添加积分商品
    """
    serializer_class = PointsMallGoodsSerializer
    permission_classes = [permissions.IsAuthenticated]
    request_body = openapi.Schema(type=openapi.TYPE_OBJECT,
                                  required=['name', 'desc', 'detail'], properties=
                                  {'name': openapi.Schema(type=openapi.TYPE_STRING, description='商品名称'),
                                   'desc': openapi.Schema(type=openapi.TYPE_STRING, description='商品简介'),
                                   'detail': openapi.Schema(type=openapi.TYPE_STRING, description='商品详情'),
                                   }
                                  )

    @swagger_auto_schema(method='post', request_body=request_body, )
    @action(methods=['post'], detail=False, )
    def post(self, request):
        form_data = AddGoodsForm(request.data)
        if not form_data.is_valid():
            return Response({'code': 407, 'message': form_data.errors})
        data = form_data.cleaned_data
        name = data.get('name')
        count = PointsMallGoods.objects.filter(name=name).count()
        if count > 0:
            return Response({'code': 407, 'message': '此商品已存在'})
        obj = PointsMallGoods(**data)
        obj.save()
        return Response({'code': 200, 'message': '添加成功'})




class PointsByGoods(generics.GenericAPIView):
    """
    积分购买商品
    """
    serializer_class = PointsMallGoodsSerializer
    permission_classes = [permissions.IsAuthenticated]
    request_body = openapi.Schema(type=openapi.TYPE_OBJECT,
                                  required=['goods_id', 'count'], properties=
                                  {'goods_id': openapi.Schema(type=openapi.TYPE_STRING, description='商品id'),
                                   'count': openapi.Schema(type=openapi.TYPE_NUMBER, description='兑换数量'),
                                   }
                                  )

    @swagger_auto_schema(method='post', request_body=request_body, )
    @action(methods=['post'], detail=False, )
    def post(self, request):
        data = request.data
        user = request.user
        data = BuyGoodsForm(data)
        if not data.is_valid():
            return Response({'code': 408, 'message': '参数异常'})
        data = data.cleaned_data
        goods_id = data.get('goods_id')
        number = data.get('count')
        goods = PointsMallGoods.objects.get(id=goods_id)
        # 验证价格是否正常
        total_count = count_goods_points(goods.price, number)
        if not total_count:
            return Response({'code': 408, 'message': '参数异常'})
        # 验证用户积分是否充足
        if user.invite_integral <= total_count:
            return Response({'code': 408, 'message': '积分不足'})
        # 开始兑换商品
        try:
            user.reduce_invite_integral(total_count, info='积分商城兑换')
            # TODO 兑换成功 商品数量减一 增加兑换记录
            return Response({'code': 200, 'message': '兑换成功'})
        except:
            error = traceback.format_exc()
            return Response({'code': 500, 'message': error})


class GetGoodsList(generics.GenericAPIView):
    """
    获取积分商品列表
    """
    serializer_class = PointsMallGoodsSerializer
    permission_classes = [permissions.IsAuthenticated]

    query_param = [openapi.Parameter(name='q', in_=openapi.IN_QUERY, description="查询条件", type=openapi.TYPE_STRING),
                   openapi.Parameter(name='size', in_=openapi.IN_QUERY, description="页数大小", type=openapi.TYPE_NUMBER),
                   openapi.Parameter(name='page', in_=openapi.IN_QUERY, description="页码", type=openapi.TYPE_NUMBER),
                   ]

    @swagger_auto_schema(method='get', manual_parameters=query_param)
    @action(methods=['get'], detail=False)
    def get(self, request):
        data = request.query_params
        q = data.get('q')
        if not q:
            result_list = PointsMallGoods.objects.order_by('-id').all()
        else:
            result_list = PointsMallGoods.objects.filter(
                Q(name__icontains=q) | Q(desc__icontains=q) | Q(detail__icontains=q)).order_by('-id')

        total_count = result_list.count()

        # 实例化分页对象
        page_cursor = LargeResultsSetPagination()
        # 分页
        data_list = page_cursor.paginate_queryset(result_list, request, view=self)

        data_list = self.get_serializer(data_list, many=True).data
        result = {'code': 200, 'data': data_list, 'total_count': total_count}
        return Response(result)


class GetPointsGoodsInfo(generics.GenericAPIView):
    """
    获取商品的详细信息
    """
    serializer_class = PointsMallGoodsSerializer
    permission_classes = [permissions.IsAuthenticated]

    query_param = [openapi.Parameter(name='goods_id', in_=openapi.IN_QUERY, description="商品id", type=openapi.TYPE_NUMBER),
                   ]

    @swagger_auto_schema(method='get', manual_parameters=query_param)
    @action(methods=['get'], detail=False)
    def get(self, request):
        data = request.query_params
        goods_id = data.get('goods_id')
        goods = PointsMallGoods.objects.get(id=goods_id)
        result = self.get_serializer(goods).data
        return Response({'code': 200, 'data': result})



